import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import {HttpException, HttpStatus, Injectable, UnauthorizedException} from '@nestjs/common';
import {AuthService} from "@/modules/auth/auth.service";
import {DbService} from "@/db/db.service";
import IHelper from "@/services/helper.service";
import {UserEntity} from "@/db/entitys/user.entity";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly dbService: DbService,) {
    super()
  }

  async validate(username: string, password: string): Promise<UserEntity> {
    const user = await this.dbService.userRepository.findOneBy({
      username, password: IHelper.md5(password)
    })
    if (!user) {
      throw new HttpException(`Username or password incorrect.`, HttpStatus.BAD_REQUEST)
    }
    return user
  }
}